package routers

import (
	"io"
	"os"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/sirupsen/logrus"

	"cvevulner/cve-ddd/app"
	"cvevulner/cve-ddd/controller"
	"cvevulner/cve-ddd/infrastructure/backendimpl"
	"cvevulner/cve-ddd/infrastructure/bulletinimpl"
	"cvevulner/cve-ddd/infrastructure/hotpatchimpl"
	"cvevulner/cve-ddd/infrastructure/latestrpmimpl"
	"cvevulner/cve-ddd/infrastructure/majunimpl"
	"cvevulner/cve-ddd/infrastructure/obsimpl"
	"cvevulner/cve-ddd/infrastructure/repositoryimpl"
	"cvevulner/cve-ddd/infrastructure/testresultimpl"
	"cvevulner/cve-ddd/infrastructure/updateinfoimpl"
)

func Init() {
	initComment()
	initController()
	InitNewRouter()
}

func InitNewRouter() {
	writers := []io.Writer{os.Stdout}
	file, err := os.OpenFile("./logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err == nil {
		writers = append(writers, file)
	} else {
		logs.Error("create log file for logrus failed: %s", err.Error())
	}

	multiWriters := io.MultiWriter(writers...)
	logrus.SetOutput(multiWriters)

	logBulletin := logrus.WithField("module", "new-security-bulletin")
	logHotPatchBulletin := logrus.WithField("module", "new-hot-patch-security-bulletin")
	logColdPatchCveCollect := logrus.WithField("module", "new-cold-patch-cve-collect")

	coldPatchService := app.NewColdPatchService(
		latestrpmimpl.NewLatestRpm(),
		repositoryimpl.NewRepositoryImpl(),
		backendimpl.NewBackendImpl(),
		updateinfoimpl.NewUpdateInfoImpl(),
		obsimpl.Instance(),
		majunimpl.NewMajunImpl(),
		logColdPatchCveCollect,
	)

	bulletinService := app.NewBulletinService(
		obsimpl.Instance(),
		repositoryimpl.NewRepositoryImpl(),
		majunimpl.NewMajunImpl(),
		bulletinimpl.NewBulletinImpl(),
		testresultimpl.NewTestResultImpl(logBulletin),
		backendimpl.NewBackendImpl(),
		logBulletin,
		updateinfoimpl.NewUpdateInfoImpl(),
	)

	hotPatchService := app.NewRefactorHotPatchService(
		repositoryimpl.NewRepositoryImpl(),
		bulletinimpl.NewBulletinImpl(),
		obsimpl.Instance(),
		updateinfoimpl.NewUpdateInfoImpl(),
		hotpatchimpl.NewHotPatchImpl(logHotPatchBulletin),
		logHotPatchBulletin,
	)

	NewCveController := controller.NewCveController(
		coldPatchService,
		bulletinService,
		hotPatchService,
		logHotPatchBulletin,
		logBulletin,
	)

	beego.Router("/security/bulletin/collect", NewCveController, "post:CollectCveData")
	beego.Router("/security/bulletin/generate", NewCveController, "post:Generate")
}
